<template>
  <div class="menu-container">
    <el-menu
      mode="horizontal"
      :default-active="activeMenu"
      @select="handleMenuSelect"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
    >
      <el-menu-item index="/">首页</el-menu-item>
      <el-sub-menu index="micro-apps" v-if="microApps.length > 0">
        <template #title>微应用</template>
        <el-menu-item v-for="app in microApps" :key="app.name" :index="app.activeRule">
          {{ app.name }}
        </el-menu-item>
      </el-sub-menu>
      <el-menu-item index="/about">关于</el-menu-item>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { microApps } from '@/micro/microApps'

console.log('microApps', microApps)

const router = useRouter()
const activeMenu = ref('/')

// 监听路由变化更新菜单选中状态
watch(
  () => router.currentRoute.value.path,
  (path) => {
    const matchedApp = microApps.find((app) => path.startsWith(<string>app.activeRule))
    activeMenu.value = <string>matchedApp?.activeRule || <string>path
  },
  { immediate: true },
)

const handleMenuSelect = (index: string) => {
  console.log('Selected menu item:', index)
  router.push(index)
}
</script>

<style lang="less" scoped>
.menu-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: @z-indexes[fixed];
  background-color: #545c64;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-menu {
    flex: 1;
    border: none;
  }

  .menu-actions {
    padding-right: @spacers[3];
    display: flex;
    align-items: center;
    gap: @spacers[2];
  }
}
</style>
